﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lan.Core
{
    public class FileHelper
    {
        public static void Write(string path, string fileName, string content)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fullPath = path + fileName;
            byte[] array = Encoding.UTF8.GetBytes(content);
            using FileStream fs = new(fullPath, FileMode.Create, FileAccess.ReadWrite);
            fs.SetLength(0);
            fs.Write(array, 0, array.Length);
        }

        public static void FileAppend(string path, string content)
        {
            byte[] array = Encoding.UTF8.GetBytes(content);
            using FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
            fs.Write(array, 0, array.Length);
        }

        public static string Read(string fullPath)
        {
            using StreamReader reader = new StreamReader(fullPath);
            string result = reader.ReadToEnd();
            return result;
        }

        public static string ReadTemplate(string fileName)
        {
            string path = "G:\\Lan\\NetCore\\LanWeb.WebApi\\Template\\" + fileName;
            return Read(path);
        }

        public static List<string> ReadFileLines(string path)
        {
            Encoding encoding = EncodingType.GetType(path);
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            if (encoding == Encoding.UTF8)
            {
                return File.ReadLines(path).ToList();
            }
            else
            {
                return File.ReadLines(path, Encoding.GetEncoding("GB2312")).ToList();
            }
        }

        public static void WriteFileLines(string path, List<string> list)
        {
            File.WriteAllLines(path, list);
        }

        public static void WriteFileLines(string path, string contents)
        {
            File.WriteAllText(path, contents);
        }
    }
}
